package server;

import java.io.FileInputStream;

/**
 * 读取class类并加载
 */
public class MyClassLoader extends ClassLoader {

    private String name;
    private String classPath;

    /**
     * 构造方法 对类路径进行赋值
     * @param classPath
     */
    public MyClassLoader(String classPath) {
        this.classPath = classPath;
    }


    @Override
    protected Class<?> findClass(String name) {
        byte[] data = getBytes(name);
        return this.defineClass(name, data, 0, data.length);
    }

    @Override
    public Class<?> loadClass(String name) {
        ClassLoader system = getSystemClassLoader();
        Class<?> aClass = null;
        try {
            aClass = system.loadClass(name);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (aClass != null) {
            return aClass;
        }

        return findClass(name);
    }

    private byte[] getBytes(String s) {

        try {
            s = s.replaceAll("\\.", "/");
            FileInputStream fis = new FileInputStream(classPath + "/" + s + ".class");
            int len = fis.available();
            byte[] data = new byte[len];
            fis.read(data);
            fis.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
